import { readRecords, readUsers } from './data';
import { LeaderboardEntry } from '@/types';

// 获取排行榜
export function getLeaderboard(categoryId: string | null = null): LeaderboardEntry[] {
  const records = readRecords();
  const users = readUsers();

  // 过滤指定分类的记录
  const filteredRecords = categoryId
    ? records.filter(r => r.categoryId === categoryId)
    : records;

  // 按用户分组统计
  const userStats = new Map<string, {
    points: number;
    bestScore: number;
    bestTime: number;
    totalChallenges: number;
  }>();

  filteredRecords.forEach(record => {
    const existing = userStats.get(record.userId) || {
      points: 0,
      bestScore: 0,
      bestTime: Infinity,
      totalChallenges: 0,
    };

    userStats.set(record.userId, {
      points: existing.points + record.points,
      bestScore: Math.max(existing.bestScore, record.score),
      bestTime: Math.min(existing.bestTime, record.timeSpent),
      totalChallenges: existing.totalChallenges + 1,
    });
  });

  // 转换为排行榜条目
  const entries: LeaderboardEntry[] = Array.from(userStats.entries()).map(([userId, stats]) => {
    const user = users.find(u => u.id === userId);
    return {
      userId,
      username: user?.username || '未知用户',
      points: stats.points,
      bestScore: stats.bestScore,
      bestTime: stats.bestTime === Infinity ? 0 : stats.bestTime,
      totalChallenges: stats.totalChallenges,
    };
  });

  // 按积分降序排序
  return entries.sort((a, b) => b.points - a.points);
}

